<?php 
/**
 * 销售
 * @copyright   Copyright (c) 2006 - 2010 DZH 友拓软件友拓通
 * @category   	账目信息
 * @package  	Model
 * @author    	李恺弘
 * @version 	2.1,2012-07-22
 */

class SaleOrderPublicModel extends RelationCommonModel {
	/// 定义真实表名
	protected 	$tableName 		= 'sale_order';
	public  	$object_type 	= 120;
	
	public $id;
	/// 定义表关联
	protected $_link	 = array('detail' => 
									array(
										'mapping_type'	=> HAS_MANY,
										'foreign_key' 	=> 'sale_order_id',
										'class_name'	=> 'sale_order_detail',
									)
								);	
	/// 自动验证设置
	protected $_validate	 =	 array(
			array("client_id",'require',"require",0), /// 0表示存在字段就验证
			array("basic_id",'require',"require",0),
			array("currency_id",'pst_integer',"require",0),
			array("order_date",'require',"require",1), ///1为必须验证
			array("expect_shipping_date",'require',"require",0), ///1为必须验证 
			array("expect_shipping_date",'order_date','expect_ship_egt_sale',2,'egtdate'), 
			array("pr_money",'Currency','valid_money',2),  
			array("",'_validDetail','require',1,'validDetail'),
			array("",'validFundsInsert','',1,'callbacks'), 	  
			array('','validQuantity','',1,'callbacks'),
		);
	///明细验证
	protected $_validDetail	 =	 array(
			array("product_id",'require','require',1),
			array("color_id",'require','require',0),
			array("size_id",'require','require',0),
			array("quantity",'currency','double',1),
			array("capability",'pst_integer','pst_integer',0),
			array("dozen",'pst_integer','pst_integer',0),
			array("price",'double','double',1),
			array('price','currency','valid_money',1),
			array("discount",'double','double',2), 
			array("discount",array(0,1),'between',2,'between'),
			array("warehouse_id",'require','require',0),
		);
	//现金验证	
	protected $_validFundsCash	 =	 array( 
			array("pay_cash_money",'require',"require",1),
			array("pay_cash_money",'double','double',1), 
		);	
	///支票验证	
	protected $_validFundsBill	 =	 array( 
			array("pay_bill_bill_date",'require','require',1), 
			array("pay_bill_bill_no",'require','require',1), 
			array("pay_bill_bill_no",'is_no','is_no',1), 
			array("pay_bill_bill_no",'require',"unique",1,'bill_no'),      
			array("pay_bill_money",'require','require',1), 
			array("pay_bill_money",'double','double',1), 
		);	
	///转账验证	
	protected $_validFundsTransfer	 =	 array( 
			array("pay_transfer_bank_id",'require','require',1), 
			array("pay_transfer_money",'require','require',1), 
			array("pay_transfer_money",'double','double',1), 
		);	
	/// 自动填充
	protected $_auto = array(
							array("create_time ", "date", 1, "function", "Y-m-d H:i:s"), /// 创建时间	
							array("update_time ", "date", 2, "function", "Y-m-d H:i:s"), /// 更新时间					
						);		
		
	/**
	 * 异步验证销售单预付款输入的规则
	 *
	 * @param array $info
	 * @return array
	 */
	public function validFunds($info){   
		$_moduleValidate	=	'_validFunds'.$info['type'];
		$this->_moduleValidation(&$this,&$info,&$_moduleValidate);   
		$error	=	array(
							'errorStatus'=>$this->errorStatus,
							'error'=>$this->error,
		);
		return $error;
	}		
		
	/**
	 * 验证保存销售单的时候输入的预付款
	 *
	 * @param array $info
	 * @return array
	 */
	public function validFundsInsert($info){    
		if ($info['pay_paid_type']>0){ 
			$pay_paid_type	=	array( 
										1=>'cash',
										2=>'bill',
										3=>'transfer',
										);
			///判断金额是否有输入
			$money_name	=	'pay_'.$pay_paid_type[$info['pay_paid_type']].'_money'; 
			if (!empty($info[$money_name])){ 
				$_moduleValidate	=	'_validFunds'.ucfirst($pay_paid_type[$info['pay_paid_type']]);
				$this->_moduleValidation(&$this,&$info,&$_moduleValidate);    
			}
		}
		return ;
	}			
		
	
	/**
	 * 初始化post信息
	 *
	 * @return array
	 */
	public function setPost(){ 
		$info=	$_POST; 
		$info['order_date_format']	=	formatDate($info['order_date'],'date');
		isset($info['pr_money']) && $info['base_pr_money']	=	$info['pr_money']; 
		foreach ($info['detail'] as $k => $v) {  
			if (is_numeric($v['discount'])){
				$info['detail'][$k]['discount']	=	1-($v['discount']*0.01);
			}else{
				if (empty($v['discount'])){
					$info['detail'][$k]['discount']	=	1;
				}
			}
		}   
		return $info; 
	}	
					
	/**
	 * 后续流程信息
	 *
	 * @return array
	 */
	public function quicklyShowSaleType(){   
		return $this->quicklyShowSaleTypeInfo($this->id);
	}

	/**
	 * 返回销售单对应后续流程的信息显示
	 *
	 * @param int $id
	 * @return array
	 */
	public function quicklyShowSaleTypeInfo($id){ 
		$sql	=	' 
		select sale_order_no as flow_no,order_date as paid_date,1 as sale_order_state,sum(quantity) as quantity,
				sum(quantity*capability*dozen) as capability,add_user,a.id as object_id,\'SaleOrder\' as object_type
				from sale_order as a inner join sale_order_detail as b on a.id=b.sale_order_id and b.sale_order_id='.$id.'
				where a.id='.$id.' group by a.id 
		union all 
		select pre_delivery_no as flow_no,pre_delivery_date as paid_date,2 as sale_order_state,sum(quantity) as quantity,
			sum(quantity*capability*dozen) as capability,add_user,a.id as object_id,\'PreDelivery\' as object_type
			from pre_delivery as a inner join pre_delivery_detail as b on a.id=b.pre_delivery_id 
			where a.sale_order_id='.$id.' group by a.id 
		union all 
		select delivery_no as flow_no,delivery_date as paid_date,3 as sale_order_state,sum(quantity) as quantity,
			sum(quantity*capability*dozen) as capability,add_user,a.id as object_id,\'Delivery\' as object_type
			from delivery as a inner join delivery_detail as b on a.id=b.delivery_id 
			where b.sale_order_id='.$id.' group by a.id  
		'; 
		$list	=	_addFlowLink(_formatList(M()->query($sql)));   
		return $list; 
	}
	
	/// 查看
	public function view(){   
		return $this->getInfo($this->id);
	}
	/// 编辑
	public function edit(){ 
		return $this->getInfo($this->id);
	} 
	
	/**
	 * 获取明细信息(用于查看/编辑)
	 *
	 * @param int $id
	 * @return array
	 */
	public  function getInfo($id) {		
		$rs 	= $this->find($id);  
		$detail	= M('sale_order_detail');
		$rs['detail'] = $detail->field('*,'.$this->getQuantityDetail('',false,true))->where('sale_order_id='.$id)->select(); 
		if (false === $rs || $rs == null) { /// 记录不存在或没权限查看该记录
			halt(L('data_right_error'));
		}			
		/// 获取客户类型
		if (C("multi_client")) {
			$client_type 		= M('Company')->field('detail_type')->select($rs['client_id']);
			$rs['detail_type'] 	= $client_type['detail_type'];
		} 
		
		$this->array_sum_money($rs['detail']);
		///款项
		$rs['fund']					= Funds($id,$this->object_type,'fundInfo'); ///预付款 
		/// 计算优惠后金额
		$rs['real_money']			=	$rs['fund']['funds']['list'][0]['dml_money'];
		///销售差异 
		if (ACTION_NAME=='view' && C('sale.relation_sale_follow_up')==1 && $rs['sale_order_state']==3){   
 			$rs['delivery']	=	$this->getDeliveryDetails($id);  
		}  
		$rs			= _formatListRelation($rs);  
		$model		= D('Gallery'); 
		$rs['pics'] = $model->getAry($id,3);    
		return $rs;
	}
	
	/**
	 * 获取发货明细
	 *
	 * @param int $sale_order_id 销售单ID
	 * @return array
	 */
	public function getDeliveryDetails($sale_order_id) {
		/// 获取是否有差异
		$rs = M('SaleDeliveryDiff')->where('sale_order_id='.$sale_order_id)->find();  
		///验证款项是否有差异 (销售单款项发货单款项有差异)
		$sale		=	M('SaleOrderDetail');
		$delivery	=	M('DeliveryDetail');
		$deliveryMoney	=	$delivery->field('sum(price*quantity*capability*dozen*discount) as money,sum(discount) as discount')
													->group('sale_order_id')->where('sale_order_id='.$sale_order_id)->find();
		$saleMoney		=	$sale->field('sum(price*quantity*capability*dozen*discount) as money')
													->group('sale_order_id')->where('sale_order_id='.$sale_order_id)->find();    		
		if ($rs || $deliveryMoney['money']!=$saleMoney['money']) { /// 有差异 
			/// 获取发货明细
			$delivery_detail = M('DeliveryDetail')
											->field('*,(quantity * capability * dozen ) as sum_quantity,
														(quantity * price * capability * dozen ) as money ,
														(quantity * price * capability * dozen ) * discount as discount_money,
														if (discount=1,"0",(1-discount)*100) as discount')
											->where('sale_order_id='.$sale_order_id)
											->select();   
			$delivery_detail	=	_formatList($delivery_detail);		  
			///判断是否有折扣金额
			$delivery_detail['list_show_discount']	= $deliveryMoney['discount']==1?false:true;  
			return $delivery_detail;
		}
	}
	
	
	/**
	 * 获取明细中的折后总金额
	 *
	 * @param array $data
	 * @return float 折后金额合计
	 */
	public function array_sum_money(&$data) {
		$sum_real_money = 0;		
		foreach ($data as $k => $list) { 
			if ($list['discount']>0){$this->list_show_discount = true;} 
			$sum_real_money+=$list['discount_money'];
		} 
		return $sum_real_money;
	}
		 
	 
	/**
	 * 所有订单列表SQL
	 *
	 * @return  array
	 */
	function indexSql(){  
		return $this->getSaleListSql(); 
	}
	
	/**
	 * 已完成订单列表SQL
	 *
	 * @return  array
	 */
	public function alistFinishSql(){ 
//		return $this->getSaleListSql(' ( need_paid<=0 || is_close>0 )');
		$where['client_paid_detail']	=	' and ( need_paid<=0 || is_close>0 ) ';
		return $this->getSaleListSql($where);
	}
	
	/**
	 * 未完成订单列表SQL
	 *
	 * @return  array
	 */
	public function alistUnfinishSql(){   
		$where['client_paid_detail']	=	' and ( need_paid>0 && is_close=0 ) ';
		return $this->getSaleListSql($where);
//		return $this->getSaleListSql(' need_paid>0 && is_close=0 and '._search_array(_getSpecialUrl($_GET)));
	}
	
	/**
	 * 组合销售单列表的SQL语句
	 *
	 * @param string $where
	 * @return array
	 */
	public  function getSaleListSql($whereArray=null){ 
		$model	=	M('sale_order');  
		$count 	= $model
						->exists('select 1 from sale_order_detail 	where sale_order_id=sale_order.id and '.getWhere($_POST['sale_order_detail']))
						->exists('select 1 from client_paid_detail 	where object_id=sale_order.id 
							and object_type=120 and '.getWhere($_POST['client_paid_detail']).$whereArray['client_paid_detail'])
						->where(getWhere($_POST['sale_order']))
						->count();  
		$this->setPage($count);  
		$ids	= $this->field('id')
						->exists('select 1 from sale_order_detail 	where sale_order_id=sale_order.id and '.getWhere($_POST['sale_order_detail']))
						->exists('select 1 from client_paid_detail 	where object_id=sale_order.id 
							and object_type=120 and '.getWhere($_POST['client_paid_detail']).$whereArray['client_paid_detail'])
						->where(getWhere($_POST['sale_order']))
						->order('sale_order_no desc')->page()->selectIds(); 
		
		$info['table'] 			= 'sale_order a 
			INNER 	JOIN sale_order_detail b ON a.id = b.sale_order_id 
			left 	JOIN client_paid_detail c ON a.id = c.object_id and c.object_type=120
			left 	JOIN sale_delivery_diff dd ON a.id = dd.sale_order_id 
			left 	join invoice_out d on d.relation_id=a.id and d.invoice_type=1';
		 
//		$info['where'] 			= _search().$where;
		$info['where'] 			= ' a.id in '.$ids;
		$info['group'] 			= 'a.id';
		$info['order'] 			= 'a.sale_order_no desc';
		$info['field'] 			= 'a.id AS id,a.sale_order_no AS sale_order_no,a.client_id AS client_id,a.basic_id AS basic_id,a.currency_id AS currency_id,a.order_date AS order_date,a.expect_shipping_date AS expect_shipping_date,a.sale_order_state AS sale_order_state,a.order_type AS order_type,a.pre_delivery AS pre_delivery,a.receive_addr AS receive_addr,a.pr_money AS pr_money,a.base_pr_money AS base_pr_money,a.base_rate AS base_rate,a.base_state AS base_state,a.comments AS comments,a.audit_state AS audit_state,a.invoice_state AS invoice_state,a.auditor AS auditor,a.audit_date AS audit_date,a.create_time AS create_time,a.update_time AS update_time,a.add_user AS add_user,a.edit_user AS edit_user,a.lock_version AS lock_version,
		'.$this->getStockStandard().' 
		,b.id AS detail_id,b.product_id AS product_id,c.is_close AS is_close,c.should_paid AS should_paid,if (is_close>0,should_paid,have_paid) AS have_paid,if (is_close>0,0,need_paid) AS need_paid,if(need_paid<=0,2,1) AS sale_order_funds,d.invoice_no,sum(if(invoice_state=2,0,1)) no_invoice,d.id invoiceOut_id,if (dd.sale_order_id>0,2,1) AS is_diff ';
//		$sql = $this->getListSql($info);
		return $sql	= 'select '.$info['field'].' from '.$info['table'].' where '.$info['where'].' group by '.$info['group'] .' order by '.$info['order']; 
	}
	
	
	/**
	 * 新增销售单,根据客户和公司获取欠款
	 *
	 * @param int $client_id
	 * @param int $basic_id
	 * @return string
	 */
	public function getClientPaidDetail($client_id,$basic_id=0){
		$str	=	'';
		$where	=	'is_close=0';
		$basic_id>0 && $where	.=' and basic_id='.$basic_id;	
		$list	= M('client_paid_detail')->field('comp_id,currency_id,basic_id,sum(need_paid*income_type*-1) as money')->where($where.' and comp_id='.$client_id)->group('comp_id,currency_id,basic_id')->select(); 
		$list	= _formatList($list);
		if (is_array($list)){
			foreach ((array)$list['list'] as $key=>$row) { 
				$str[]	=	$row['currency_no'].':'.$row['dml_money'];
			} 
			$str	=	' '.L('need_paid_money').':('.join(' ',$str).')';
		}
		return $str;
	}
	
}